package vip.xiaonuo.biz.core.config;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import vip.xiaonuo.biz.modular.Englishword.result.QianWenResult;
import vip.xiaonuo.common.exception.CommonException;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;

@Getter
@Configuration
@Slf4j
public class QianWenConfig {

    @Value("${aliyun.api-key}")
    private String apiKey;

    @Value("${aliyun.base-url}")
    private String baseUrl;

    @Value("${aliyun.endpoint}")
    private String endpoint;

    @Value("${aliyun.model-name}")
    private String modelName;


    private static String promptRoleTxt;

    static {
        // springboot读取resources/prompt/input.txt目录下的input.txt文件
        try {
            String path = "prompt/input.txt";
            ClassLoader classLoader = QianWenConfig.class.getClassLoader();
            java.net.URL resource = classLoader.getResource(path);
            Path filePath = null;
            if (resource != null) {
                filePath = Path.of(resource.toURI());
            }
            String content = null;
            if (filePath != null) {
                content = Files.readString(filePath);
            }
            log.info(content);
            promptRoleTxt=content;
        } catch (Exception e) {
            log.error("读取prompt/input.txt文件失败",e);
        }
    }

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder
                .setConnectTimeout(Duration.ofSeconds(5))
                .setReadTimeout(Duration.ofSeconds(5))
                .build();
    }


    static class Message {
        String role;
        String content;

        public Message(String role, String content) {
            this.role = role;
            this.content = content;
        }
    }

    static class RequestBody {
        String model;
        Message[] messages;

        public RequestBody(String model, Message[] messages) {
            this.model = model;
            this.messages = messages;
        }
    }

    /**
     * 发送消息
     *
     * @param promptTxt 提示txt
     * @return {@link QianWenResult}
     */
    public QianWenResult sendWordTxt(String promptTxt,Integer wordNum) {
        try {
            promptRoleTxt = promptRoleTxt.replace("{{articleNum}}", String.valueOf(wordNum));
            RequestBody requestBody = new RequestBody(
                    getModelName(),
                    new Message[] {
                            new Message("system", promptRoleTxt),
                            new Message("user", promptTxt)
                    }
            );

            // 将请求体转换为 JSON
            Gson gson = new Gson();
            String jsonInputString = gson.toJson(requestBody);

            // 创建 URL 对象
            URL url = new URL(getEndpoint());
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为 POST
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Content-Type", "application/json; utf-8");
            httpURLConnection.setRequestProperty("Accept", "application/json");

            // 若没有配置环境变量，请用百炼API Key将下行替换为：String apiKey = "sk-xxx";
            String apiKey = getApiKey();
            String auth = "Bearer " + apiKey;
            httpURLConnection.setRequestProperty("Authorization", auth);

            // 启用输入输出流
            httpURLConnection.setDoOutput(true);

            // 写入请求体
            try (OutputStream os = httpURLConnection.getOutputStream()) {
                byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 获取响应码
            int responseCode = httpURLConnection.getResponseCode();
            log.info("Response Code: {}", responseCode);

            // 读取响应体
            try (BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                QianWenResult qianWenResult = JSON.parseObject(response.toString(), QianWenResult.class);
                log.info("Response Body: {}", qianWenResult);
                return qianWenResult;
            }
        } catch (Exception e) {
            throw new CommonException("当前AI服务不可用，请使用快照模式",e);
        }
    }

}
